//
//  CMURegisterController.m
//  BoonApp
//
//  Created by Liuyi Sun on 10/1/12.
//  Copyright (c) 2012 CMU. All rights reserved.
//

#import "CMURegisterController.h"

@interface CMURegisterController ()

@end

@implementation CMURegisterController
@synthesize firstName = firstName_ ;
@synthesize lastName = lastName_ ;  
@synthesize address = address_ ;
@synthesize password = password_ ;
@synthesize responseData = _responseData;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.firstName = @"";
    self.lastName = @"";
    self.address     = @"" ;
	self.password    = @"" ;
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 4;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    
    // Make cell unselectable
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
	
	UITextField* tf = nil ;
	switch ( indexPath.row ) {
        case 0: {
            cell.textLabel.text = @"First Name" ;
			tf = firstNameField_ = [self makeTextField:self.firstName placeholder:@"Jim"];
			[cell addSubview:firstNameField_];
			break ;
        }
        case 1: {
            cell.textLabel.text = @"Last Name" ;
			tf = lastNameField_ = [self makeTextField:self.lastName placeholder:@"Smith"];
			[cell addSubview:lastNameField_];
			break ;
        }
		case 2: {
			cell.textLabel.text = @"Email" ;
			tf = addressField_ = [self makeTextField:self.address placeholder:@"example@gmail.com"];
            tf.keyboardType = UIKeyboardTypeEmailAddress;
			[cell addSubview:addressField_];
			break ;
		}
		case 3: {
			cell.textLabel.text = @"Password" ;
			tf = passwordField_ = [self makeTextField:self.password placeholder:@"Required"];
            tf.secureTextEntry = YES;
			[cell addSubview:passwordField_];
			break ;
		}
	}
    
	// Textfield dimensions
	tf.frame = CGRectMake(120, 12, 170, 30);
	
	// Workaround to dismiss keyboard when Done/Return is tapped
	[tf addTarget:self action:@selector(textFieldFinished:) forControlEvents:UIControlEventEditingDidEndOnExit];
	
	// We want to handle textFieldDidEndEditing
	tf.delegate = self;
    
    return cell;
}

-(UITextField*) makeTextField: (NSString*)text
                  placeholder: (NSString*)placeholder  {
	UITextField *tf = [[UITextField alloc] init];
	tf.placeholder = placeholder ;
	tf.text = text ;
	tf.autocorrectionType = UITextAutocorrectionTypeNo ;
	tf.autocapitalizationType = UITextAutocapitalizationTypeNone;
	tf.adjustsFontSizeToFitWidth = YES;
	tf.textColor = [UIColor colorWithRed:56.0f/255.0f green:84.0f/255.0f blue:135.0f/255.0f alpha:1.0f];
	return tf ;
}

// Workaround to hide keyboard when Done is tapped
- (IBAction)textFieldFinished:(id)sender {
    // [sender resignFirstResponder];
}

// Textfield value changed, store the new value.
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if(textField == firstNameField_){
        self.firstName = textField.text;
    } else if(textField == lastNameField_){
        self.lastName = textField.text ;
    } else if ( textField == addressField_ ) {
		self.address = textField.text ;
	} else if ( textField == passwordField_ ) {
		self.password = textField.text ;
	}
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"didReceiveResponse");
    // This method is called when the server has determined that it
    // has enough information to create the NSURLResponse.
    
    // It can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.
    
    // receivedData is an instance variable declared elsewhere.
    [self.responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to receivedData.
    // receivedData is an instance variable declared elsewhere.
    [self.responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // inform the user
    NSLog(@"didFailWithError");
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (IBAction)testScan:(id)sender {
    // ADD: present a barcode reader that scans from the camera feed
    ZBarReaderViewController *reader = [ZBarReaderViewController new];
    reader.readerDelegate = self;
    reader.supportedOrientationsMask = ZBarOrientationMaskAll;
    
    ZBarImageScanner *scanner = reader.scanner;
    // TODO: (optional) additional reader configuration here
    
    // EXAMPLE: disable rarely used I2/5 to improve performance
    [scanner setSymbology: ZBAR_I25
                   config: ZBAR_CFG_ENABLE
                       to: 0];
    
    // present and release the controller
    [self presentViewController: reader animated: YES completion: ^(){
        NSLog(@"Completed!");
    }];
    
}

- (void) imagePickerController: (UIImagePickerController*) reader
 didFinishPickingMediaWithInfo: (NSDictionary*) info
{
    // ADD: get the decode results
    id<NSFastEnumeration> results =
    [info objectForKey: ZBarReaderControllerResults];
    ZBarSymbol *symbol = nil;
    for(symbol in results)
        // EXAMPLE: just grab the first barcode
        break;
    
    // EXAMPLE: do something useful with the barcode data
    self.qrcode.text = symbol.data;
        
    // EXAMPLE: do something useful with the barcode image
//    self.imageView.image = [info objectForKey: UIImagePickerControllerOriginalImage];
    
    // ADD: dismiss the controller (NB dismiss from the *reader*!)
    [reader dismissViewControllerAnimated: YES completion:^(){}];
}

- (IBAction)actionRegister:(id)sender {
    NSLog(@"viewdidload");
    [self performSegueWithIdentifier:@"toLogin" sender:nil];
    self.responseData = [NSMutableData data];
    NSString *registerServiceURL = [[NSString alloc] initWithFormat:@"http://98.142.220.113:3000/consumerLogin.json?username=%@&password=%@", self.address,self.password];
    NSLog(@"%@",registerServiceURL);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:registerServiceURL]];
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (theConnection) {
        // Create the NSMutableData to hold the received data.
        // receivedData is an instance variable declared elsewhere.
        NSLog(@"Connect successfully!");
    } else {
        // Inform the user that the connection failed.
    }

}
@end
